#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <iostream>
#include <string>
#include <cerrno>
#include <unistd.h>

int main(int argc, char **argv)
{
    if (argc != 3)
    {
        std::cout << "Usage" << argv[0] << " ip"
                  << " port" << std::endl;
        return 1;
    }

    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        std::cerr << "socket error: " << errno << std::endl;
        return 2;
    }
    struct sockaddr_in peer_addr;
    memset(&peer_addr, 0, sizeof(peer_addr));
    peer_addr.sin_family = AF_INET;
    peer_addr.sin_addr.s_addr = inet_addr(argv[1]);
    peer_addr.sin_port = htons(atoi(argv[2]));

    socklen_t peer_addr_len = sizeof(peer_addr);

    if (connect(sock, (struct sockaddr *)&peer_addr, peer_addr_len) < 0)
    {
        std::cout << "connect server failed !" << std::endl;
        return 3;
    }
    char buffer[1024];

    while (1)
    {
        memset(buffer,0,sizeof(buffer));
        std::cout << "Please Enter# ";
        fgets(buffer, sizeof(buffer) - 1, stdin);
        buffer[strlen(buffer)-1] = '\0'; //吃掉fets的\n
        write(sock, buffer, strlen(buffer));

        ssize_t s = read(sock, buffer, sizeof(buffer) - 1);
        if (s > 0)
        {
            buffer[s] = 0;
            std::cout << "server echo# " << buffer << std::endl;
        }
    }
}